package jd.se.book;

import jd.se.common.CurrentUser;
import jd.se.common.Result;
import jd.se.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


@WebServlet({
        "/book/bookList",
        "/book/addborrow_info",
})
public class BookAPI extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BookService service = new BookService();
        request.setCharacterEncoding("UTF-8");
        String path = request.getServletPath();
        if("/book/addborrow_info".equals(path)){
            CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
            BorrowDto dto = Utils.getBeanFromRequest(BorrowDto.class,request);
            service.addborrow_info(dto, currentUser);
            Utils.outJson(response, Result.success());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //接收客户端（浏览器）传来的参数,并将参数封装为Java对象
        request.setCharacterEncoding("UTF-8");
        //创建并获取需求表
        QueryDto queryDto = new QueryDto();
        try {
            queryDto.setPageNum(Integer.parseInt(request.getParameter("pageNum")));
        } catch (Exception e) {}

        try {
            queryDto.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
        } catch (Exception e) {}
        queryDto.setB_name(request.getParameter("b_name"));
        try {
            queryDto.setAuthor(request.getParameter("author"));
        } catch (Exception e) {}
        queryDto.setPress(request.getParameter("press"));
        try {
            queryDto.setStatus(Integer.parseInt(request.getParameter("status")));
        } catch (Exception e){}


        //创建业务模型对象（服务对象/Service对象），通过业务对象执行业务方法
        BookService service = new BookService();
        Map<String,Object> page =  service.getBookList(queryDto);

        //通过视图生成json
        Utils.outResult(response, Result.success(page));
    }
}
